package joq.server;

import java.util.NoSuchElementException;

/**
 * Container class for message contents.
 * @author jeff
 */
public class Message
{
    /**
     * Describes the type of operation requested, with PUT equating to adding
     * onto the queue, and GET removing from the queue.
     */
    public enum TYPE
    {
	PUT,
	GET
    };

    private TYPE type;
    private String message;
    private String[] tags;

    /**
     * Builds a "PUT" message.
     * @param message
     * @param tags
     */
    Message(String message, String[] tags)
    {
	this.tags = tags;
	this.message = message;
	this.type = Message.TYPE.PUT;
    }

    /**
     * Builds a "GET" message.
     * @param tags
     */
    Message(String[] tags)
    {
	this.tags = tags;
	this.type = Message.TYPE.GET;
    }

    public TYPE getType()
    {
	return type;
    }

    public String getMessage() throws NoSuchElementException
    {
	if (type == Message.TYPE.PUT)
	    return message;
	else
	    throw new NoSuchElementException();
    }

    public String[] getTags()
    {
	return tags;
    }

    @Override
    public String toString()
    {
	StringBuilder buf = new StringBuilder();
	buf.append(type == TYPE.GET ? "get" : "put").append(" ");

	for (int i = 0; i < tags.length; ++i) {
	    buf.append(tags[i]);
	    if (i < tags.length - 1)
		buf.append(",");
	}

	if (type == TYPE.PUT)
	    buf.append(" ").append(message);

	buf.append("\n");
	return buf.toString();
    }
}
